import { Request, Response } from 'express';
import mockData from './mockData.json';

// 辅助函数：查找最小的可用 id
function findMinAvailableId(dataSource: any[]): number {
    const existingIds = dataSource.map((item) => item.id).sort((a, b) => a - b);
    let minAvailableId = 1;

    for (const id of existingIds) {
        if (id === minAvailableId) {
            minAvailableId++;
        } else if (id > minAvailableId) {
            break;
        }
    }

    return minAvailableId;
}

export default {
    // 获取管理员列表
    'GET /api/admins': (req: Request, res: Response) => {
        const page = Number(req.query.page) || 1;
        const pageSize = Number(req.query.pageSize) || 10;
        const start = (page - 1) * pageSize;
        const end = start + pageSize;
        const dataSource = mockData.data.dataSource.slice(start, end);

        res.json({
            success: true,
            data: {
                dataSource,
                meta: {
                    total: mockData.data.dataSource.length,
                    page,
                    per_page: pageSize,
                },
            },
        });
    },

    // 删除管理员
    'POST /api/admins/delete': (req: Request, res: Response) => {
        const { id } = req.body;
        mockData.data.dataSource = mockData.data.dataSource.filter(
            (item: any) => !id.includes(item.id)
        );
        res.json({ success: true, message: 'Deleted successfully' });
    },

    // 创建管理员
    'POST /api/admins/add': (req: Request, res: Response) => {
        const minAvailableId = findMinAvailableId(mockData.data.dataSource);
        const newAdmin = {
            id: minAvailableId, // 使用最小的可用id
            ...req.body,
            create_time: new Date().toISOString(),
            status: 1,
            groups: [],
        };
        mockData.data.dataSource.unshift(newAdmin);
        res.json({ success: true, message: 'Added successfully' });
    },

    // 更新管理员
    'PUT /api/admins/:id': (req: Request, res: Response) => {
        const { id } = req.params;
        const index = mockData.data.dataSource.findIndex(
            (item: any) => item.id === Number(id)
        );
        if (index !== -1) {
            mockData.data.dataSource[index] = {
                ...mockData.data.dataSource[index],
                ...req.body,
            };
        }
        res.json({ success: true, message: 'Updated successfully' });
    },
};